/**$Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *   Copyright (C) 2008 - 2013 xingsheng.zhu@gmail.com All rights reserved.
 */
package com.blazemina.executor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * executorgroup的配置内容
 * 
 * {@link #groupSize}此变量设置为2的
 * @author JackChu
 * @version 2.0.0 2013-2-21 下午1:36:35
 */
public class ExecutorGroup {

	private String groupName;

	private boolean sequence;

	private int groupSize;

	private ExecutorService[] sequenceExecutorServices;
	
	private final ConcurrentHashMap<Integer, ExecutorService> executorServices = new ConcurrentHashMap<Integer, ExecutorService>();

	private ExecutorService unSequenceExecutorService;

	/**
	 * 
	 * @param groupName
	 * @param groupSize
	 * @param sequence
	 */
	public ExecutorGroup(String groupName, int groupSize, boolean sequence) {
		this.groupName = groupName;
		this.groupSize = groupSize;
		this.sequence = sequence;
		init();
	}

	void init() {
		if (sequence) {
			sequenceExecutorServices = new ExecutorService[groupSize];
			for (int i = 0; i < groupSize; i++) {
				sequenceExecutorServices[i] = Executors
						.newSingleThreadExecutor();
			}
		} else {
			unSequenceExecutorService = Executors.newFixedThreadPool(groupSize);
		}
	}
	
	/**
	 * 
	 * @param routeInfo
	 * @return
	 */
	public ExecutorService getExecutor(RouteInfo routeInfo) {
		if (sequence) {
			if(groupSize == 1){
				return sequenceExecutorServices[0];
			}else{
				return executorServices.putIfAbsent(routeInfo.getInfo(), sequenceExecutorServices[routeInfo.getInfo()&(groupSize-1)]);
			}
		} else {
			return unSequenceExecutorService;
		}
	}

}
